package com.tulele.vtool.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tulele.vtool.mapper.BPosterDetailsMapper;
import com.tulele.vtool.mapper.BPosterHistoryMapper;
import com.tulele.vtool.mapper.BPosterInfoMapper;
import com.tulele.vtool.mapper.UserInfoMapper;
import com.tulele.vtool.model.*;
import com.tulele.vtool.qrcode.QRCodeUtil;
import com.tulele.vtool.service.BPosterInfoService;
import com.tulele.vtool.service.SysGzhService;
import com.tulele.vtool.utils.*;
import com.tulele.vtool.wechat.service.WeixinServiceDL;
import com.tulele.vtool.wechat.service.WeixinServiceMap;
import io.lkt.common.utils.DateUtils;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.*;
import java.util.List;

import static com.tulele.vtool.utils.AesExpand.aesDecrypt;
import static com.tulele.vtool.utils.CutImages.*;

/**
 * 海报信息表(BPosterInfo)表服务实现类
 *
 * @author makejava
 * @since 2020-11-27
 */
@Slf4j
@Service("bPosterInfoService")
public class BPosterInfoServiceImpl implements BPosterInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private BPosterInfoMapper bPosterInfoMapper;

    @Autowired
    private BPosterDetailsMapper bPosterDetailsMapper;

    @Autowired
    private BPosterHistoryMapper bPosterHistoryMapper;

    @Autowired
    private SysGzhService sysGzhService;

    @Autowired
    private ObjectFactory<WeixinServiceDL> objectFactory;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public BPosterInfo queryById(Integer id) {
        return this.bPosterInfoMapper.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<BPosterInfo> queryAllByLimit(int offset, int limit) {
        return this.bPosterInfoMapper.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param bPosterInfo 实例对象
     * @return 实例对象
     */
    @Override
    public BPosterInfo insert(BPosterInfo bPosterInfo) {
        this.bPosterInfoMapper.insert(bPosterInfo);
        return bPosterInfo;
    }

    /**
     * 修改数据
     *
     * @param bPosterInfo 实例对象
     * @return 实例对象
     */
    @Override
    public BPosterInfo update(BPosterInfo bPosterInfo) {
        this.bPosterInfoMapper.update(bPosterInfo);
        return this.queryById(bPosterInfo.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.bPosterInfoMapper.deleteById(id) > 0;
    }

    /**
     * 查询多条数据
     *
     * @param bPosterInfo 实例对象
     * @return 对象列表
     */
    @Override
    public PageInfo selectAllByLimit(BPosterInfo bPosterInfo) {

        PageHelper.startPage(bPosterInfo.getPageNum(), bPosterInfo.getPageSize());

        bPosterInfo.setStatus(1); //删除状态 0-删除 1-正常
        List<BPosterInfo> bPosterInfoList = this.bPosterInfoMapper.queryAll(bPosterInfo);

        return new PageInfo<BPosterInfo>(bPosterInfoList);
    }

    /**
     * 合成海报
     *
     * @param userId               用户 userId
     * @param springProfilesActive 公众号标识
     * @param bPosterInfo          实例对象
     * @return 单条数据
     */
    @Override
    public String creatByInfoKey(String userId, String springProfilesActive, BPosterInfo bPosterInfo) throws Exception {

        // 图片结果路径
        String outputImgPath = "";

        // 查询用户基础信息
        Integer userIdInt = Integer.valueOf(userId);
        UserInfo userInfo = this.userInfoMapper.queryUserInfo(userIdInt);

        PlatformSysInfo platformSysInfoConfig = this.sysGzhService.getPlatformSysInfo(springProfilesActive);

        if (userInfo == null) {
            return "请先完善个人信息";
        }

        // 解密id
        Integer id = Integer.valueOf(aesDecrypt(bPosterInfo.getInfoKey(), SysConstant.KEY));
//        infoKey = aesEncrypt(id.toString(), SysConstant.KEY);

        BPosterInfo posterInfo = this.bPosterInfoMapper.queryById(id);
        if (posterInfo == null) {
            return "无效海报模板";
        }

//        // 查询一下海报生成记录
//        BPosterHistory temporary = new BPosterHistory();
//
//        temporary.setGzhCode(posterInfo.getGzhCode());
//        temporary.setUserId(userIdInt);
//        temporary.setPosterId(id);
//        temporary.setName(bPosterInfo.getPosterName());
//        temporary.setPhone(bPosterInfo.getPosterPhone());
//        temporary.setComp(bPosterInfo.getPosterComp());
//        temporary.setStatus(1);
//
//        String result = this.bPosterHistoryMapper.queryOne(temporary);
//
//        // 如果之前海报生成过直接返回
//        if (StringUtils.isNotBlank(result) && result.contains(SysConstant.CREAT_POSTER_PICTURE_OSS_ACCESS_PREFIX + SysConstant.CREAT_POSTER_PICTURE_OSS_DIR + userId)) {
//            return result;
//        }

        // 会员状态
        int vipStatus = Optional.ofNullable(userInfo.getVipStatus()).orElse(0);

        // 会员海报模板
        if (posterInfo.getMember() == 1 && vipStatus != 1) {
            return "会员海报模板，您还不是会员";
        }

        // 姓名
        String posterName = bPosterInfo.getPosterName();

        // 电话
        String posterPhone = bPosterInfo.getPosterPhone();

        // 公司
        String posterComp = bPosterInfo.getPosterComp();

        // 头像
        String posterHeard = bPosterInfo.getPosterHeard();

        // 文字1
        String posterText1 = bPosterInfo.getPosterText1();

        // 文字2
        String posterText2 = bPosterInfo.getPosterText2();

        // 文字3
        String posterText3 = bPosterInfo.getPosterText3();

        BPosterDetails bPosterDetails = new BPosterDetails();
        bPosterDetails.setType(id);
        bPosterDetails.setStatus(1); // 删除状态 0-删除 1-正常
        List<BPosterDetails> infoList = this.bPosterDetailsMapper.queryAll(bPosterDetails);

        if (CollectionUtils.isNotEmpty(infoList)) {
            // 海报背景图片宽度、高度、底图数量
            int bcgW = 750;
            int bcgH = 1330;
            int bgNUm = 0;

            for (BPosterDetails infod : infoList) {
                if (infod.getItem() == 1011) {
                    bcgW = infod.getWidth();
                    bcgH = infod.getHeight();
                    bgNUm = bgNUm + 1;
                }
            }

            // 按照底图的宽高生成新的图片
            BufferedImage bfImage = new BufferedImage(bcgW, bcgH, BufferedImage.TYPE_INT_RGB);
            // 开启画笔
            Graphics2D g = bfImage.createGraphics();
            // 去毛边
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);


            for (BPosterDetails info : infoList) {
                // 类型
                Integer item = info.getItem();
                // 宽度
                Integer w = info.getWidth();
                // 高度
                Integer h = info.getHeight();
                // 左边距离
                Integer l = info.getLefts();
                // 上边距离
                Integer t = info.getTop();
                // 是否圆角
                Integer r = info.getRadius();
                // 角度
                Integer ro = info.getRotate();
                // 图片url
                String url = info.getImange();
                // 文字颜色
                String colorHex = info.getColor();
                // 文字大小
                Integer fontSize = 26;

                // 如果是用户的头像
                if (item == 1012) {
                    // 查询用户的头像
                    if (posterHeard != null && StringUtils.isNotBlank(posterHeard)) {
                        url = posterHeard;
                    } else if (userInfo != null && StringUtils.isNotBlank(userInfo.getAvatarUrl())) {
                        url = userInfo.getAvatarUrl();
                    } else {
                        // 关闭画笔
                        g.dispose();
                        return "请先完善头像";
                    }
                }

//                // 如果是用户的二维码
//                if (item == 1013) {
//
//                    // 查询用户的二维码
//                    if (userInfo != null && !StringUtils.isBlank(userInfo.getQrcodeUrl())) {
//                        url = userInfo.getQrcodeUrl();
//                    } else {
//                        // 关闭画笔
//                        g.dispose();
//                        return "请先完善推广二维码";
//                    }
//                }

                // 将图片url转换成 BufferedImage
                BufferedImage bimg = null;
                if (StringUtils.isNotBlank(url) && (item == 1011 || item == 1012 || item == 1014)) {
                    try {
                        URL urlfile = new URL(url.replaceAll("(/132)+$", "/0"));
                        InputStream inStream = urlfile.openStream();
                        bimg = ImageIO.read(inStream);
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.info("********** 转换异常 **********");
                    }
                }

                Color colorRgb = new Color(0, 0, 0);

                if (StringUtils.isNotBlank(colorHex) && colorHex.contains("#") && (item == 1015 || item == 1016 || item == 1017 || item == 1018 || item == 1019 || item == 1020)) {

                    colorRgb = Color.decode(colorHex);
                }

                if (info.getSize() >= 12 && (item == 1015 || item == 1016 || item == 1017 || item == 1018 || item == 1019 || item == 1020)) {

                    fontSize = info.getSize();
                }
                // 文字大小
                Font font = new Font("微软雅黑", Font.PLAIN, fontSize);

                switch (item) {
                    case 1011:
                        log.info("********** 海报底图 **********");

                        if (bimg != null) {
                            // 画海报背景图片
                            g.rotate(Math.toRadians(ro), l + w / 2, t + h / 2);
                            g.drawImage(bimg, 0, 0, bcgW, bcgH, null);
                            g.rotate(Math.toRadians(-ro), l + w / 2, t + h / 2);
                        }

                        break;
                    case 1012:
                        log.info("********** 头像 **********");

                        if (bimg != null) {

                            // 头像处理，头像半径大于等于短边的一般，变圆形。
                            if (r > 0 && r >= (w < h ? w : h) / 2) {
                                bimg = cutHeadImages1(url);
                            }

//                            bimg = getScaledImage(bimg, 750, 2);

                            // 画海报头像图片
                            g.rotate(Math.toRadians(ro), l + w / 2, t + h / 2);
                            g.drawImage(bimg, l, t, w, h, null);
                            g.rotate(Math.toRadians(-ro), l + w / 2, t + h / 2);
                        }

                        break;
                    case 1013:
                        log.info("********** 推广二维码 **********");

                        // 存放在二维码中的内容，fromPage=1_海报加密id（通过 海报页面 到 微商页面）
                        String text = SysConstant.WEI_ZHAN_PATH.replace(SysConstant.frontDomain, platformSysInfoConfig.getFrontDomain()) + userId + "&fromPage=1_" + id + "&v=97";
                        // text = "http://zktmessage.zhanxiaobai.net//pages/home/index.html?closeW=false&otherUserId=723136&fromPage=1_bGQc/qZTg1blPBfrAqCfmA==&v=97";
                        // 嵌入二维码的图片路径

                        System.out.println(text);
                        String imgPath = "D:/temp/image/zhihu/v2-1ea1f4b00aac61996d58f7fedcc80058_hd.jpg";
                        imgPath = "";
                        //生成二维码
                        BufferedImage qrCodePath = QRCodeUtil.encodeReturnBufferedImage(text, imgPath, false);

                        // 画海报推广二维码图片
                        g.rotate(Math.toRadians(ro), l + w / 2, t + h / 2);
                        g.drawImage(qrCodePath, l, t, w, h, null);
                        g.rotate(Math.toRadians(-ro), l + w / 2, t + h / 2);

                        break;
                    case 1014:
                        log.info("********** 推广大图 **********");

                        if (bimg != null) {
                            // 画海报推广大图片图片
                            g.rotate(Math.toRadians(ro), l + w / 2, t + h / 2);
                            g.drawImage(bimg, l, t, w, h, null);
                            g.rotate(Math.toRadians(-ro), l + w / 2, t + h / 2);
                        }

                        break;
                    case 1015:
                        if (StringUtils.isNotBlank(posterName)) {
                            log.info("姓名：" + posterName);

                            // 图片上写文字
                            g.setFont(font);
                            g.setColor(colorRgb);

                            FontMetrics fm = sun.font.FontDesignMetrics.getMetrics(font);
                            // 整个字符串的宽度
                            int widthN = fm.stringWidth(posterName);
                            // 字符串的高度
                            int heightN = fm.getHeight();

                            // 可以看出Height = Ascent + Descent + Leading
                            int ascent = fm.getAscent();
                            int descent = fm.getDescent();
                            int leading = fm.getLeading();
                            int height = fm.getHeight();
                            System.out.println("姓名：" + posterName);
                            System.out.printf("Height = %d\tAscent = %d\tDescent = %d\tLeading = %d", height, ascent, descent, leading);

                            g.rotate(Math.toRadians(ro), l + w / 2, t + h / 2);

                            // 1px = 0.75pt
                            g.drawString(posterName, l, t + ascent - descent);
                            g.rotate(Math.toRadians(-ro), l + w / 2, t + h / 2);
                        }
                        break;
                    case 1016:
                        if (StringUtils.isNotBlank(posterPhone)) {
                            log.info("电话：" + posterPhone);

                            // 图片上写文字
                            g.setFont(font);
                            g.setColor(colorRgb);

                            FontMetrics fm = sun.font.FontDesignMetrics.getMetrics(font);
                            // 整个字符串的宽度
                            int widthP = fm.stringWidth(posterPhone);
                            // 字符串的高度
                            int heightP = fm.getHeight();

                            // 可以看出Height = Ascent + Descent + Leading
                            int ascent = fm.getAscent();
                            int descent = fm.getDescent();
                            int leading = fm.getLeading();
                            int height = fm.getHeight();
                            System.out.println("电话：" + posterPhone);
                            System.out.printf("Height = %d\tAscent = %d\tDescent = %d\tLeading = %d", height, ascent, descent, leading);

                            g.rotate(Math.toRadians(ro), l + w / 2, t + h / 2);

                            // 1px = 0.75pt
                            g.drawString(posterPhone, l, t + ascent - descent);
                            g.rotate(Math.toRadians(-ro), l + w / 2, t + h / 2);
                        }
                        break;
                    case 1017:
                        if (StringUtils.isNotBlank(posterComp)) {
                            log.info("公司：" + posterComp);

                            // 图片上写文字
                            g.setFont(font);
                            g.setColor(colorRgb);

                            FontMetrics fm = sun.font.FontDesignMetrics.getMetrics(font);
                            // 整个字符串的宽度
                            int widthC = fm.stringWidth(posterComp);
                            // 字符串的高度
                            int heightC = fm.getHeight();

                            // 可以看出Height = Ascent + Descent + Leading
                            int ascent = fm.getAscent();
                            int descent = fm.getDescent();
                            int leading = fm.getLeading();
                            int height = fm.getHeight();
                            System.out.println("公司：" + posterComp);
                            System.out.printf("Height = %d\tAscent = %d\tDescent = %d\tLeading = %d", height, ascent, descent, leading);

                            g.rotate(Math.toRadians(ro), l + w / 2, t + h / 2);

                            // 1px = 0.75pt
                            g.drawString(posterComp, l, t + ascent - descent);
                            g.rotate(Math.toRadians(-ro), l + w / 2, t + h / 2);
                        }
                        break;
                    case 1018:
                        if (StringUtils.isNotBlank(posterText1)) {
                            log.info("文字1：" + posterText1);

                            // 图片上写文字
                            g.setFont(font);
                            g.setColor(colorRgb);

                            FontMetrics fm = sun.font.FontDesignMetrics.getMetrics(font);
                            // 整个字符串的宽度
                            int widthT1 = fm.stringWidth(posterText1);
                            // 字符串的高度
                            int heightT1 = fm.getHeight();

                            // 可以看出Height = Ascent + Descent + Leading
                            int ascent = fm.getAscent();
                            int descent = fm.getDescent();
                            int leading = fm.getLeading();
                            int height = fm.getHeight();
                            System.out.println("文字1：" + posterText1);
                            System.out.printf("Height = %d\tAscent = %d\tDescent = %d\tLeading = %d", height, ascent, descent, leading);

                            g.rotate(Math.toRadians(ro), l + w / 2, t + h / 2);

                            // 1px = 0.75pt
                            g.drawString(posterText1, l, t + ascent - descent);
                            g.rotate(Math.toRadians(-ro), l + w / 2, t + h / 2);
                        }
                        break;
                    case 1019:
                        if (StringUtils.isNotBlank(posterText2)) {
                            log.info("文字2：" + posterText2);

                            // 图片上写文字
                            g.setFont(font);
                            g.setColor(colorRgb);

                            FontMetrics fm = sun.font.FontDesignMetrics.getMetrics(font);
                            // 整个字符串的宽度
                            int widthT2 = fm.stringWidth(posterText2);
                            // 字符串的高度
                            int heightT2 = fm.getHeight();

                            // 可以看出Height = Ascent + Descent + Leading
                            int ascent = fm.getAscent();
                            int descent = fm.getDescent();
                            int leading = fm.getLeading();
                            int height = fm.getHeight();
                            System.out.println("文字2：" + posterText2);
                            System.out.printf("Height = %d\tAscent = %d\tDescent = %d\tLeading = %d", height, ascent, descent, leading);

                            g.rotate(Math.toRadians(ro), l + w / 2, t + h / 2);

                            // 1px = 0.75pt
                            g.drawString(posterText2, l, t + ascent - descent);
                            g.rotate(Math.toRadians(-ro), l + w / 2, t + h / 2);
                        }
                        break;
                    case 1020:
                        if (StringUtils.isNotBlank(posterText3)) {
                            log.info("文字3：" + posterText3);

                            // 图片上写文字
                            g.setFont(font);
                            g.setColor(colorRgb);

                            FontMetrics fm = sun.font.FontDesignMetrics.getMetrics(font);
                            // 整个字符串的宽度
                            int widthT3 = fm.stringWidth(posterText3);
                            // 字符串的高度
                            int heightT3 = fm.getHeight();

                            // 可以看出Height = Ascent + Descent + Leading
                            int ascent = fm.getAscent();
                            int descent = fm.getDescent();
                            int leading = fm.getLeading();
                            int height = fm.getHeight();
                            System.out.println("文字3：" + posterText3);
                            System.out.printf("Height = %d\tAscent = %d\tDescent = %d\tLeading = %d", height, ascent, descent, leading);

                            g.rotate(Math.toRadians(ro), l + w / 2, t + h / 2);

                            // 1px = 0.75pt
                            g.drawString(posterText3, l, t + ascent - descent);
                            g.rotate(Math.toRadians(-ro), l + w / 2, t + h / 2);
                        }
                        break;
                    default:
                        log.info("未知 item");
                }
                log.info("你的 item 是 " + item + "\n");

            }

            // 关闭画笔
            g.dispose();

            // 输入流
            File targetFileImg = null;
            // 文件名
            String fileName = UUID.randomUUID().toString() + ".png";
//            fileName = "test.png";

            try {
                // 临时文件
                targetFileImg = File.createTempFile(UUID.randomUUID().toString(), "tmp");
                ImageIO.write(bfImage, "png", targetFileImg);

                log.info("[Poster-Image-Name] = " + fileName);

                String formatDate = DateUtil.getFormatDate("yyyy-MM-dd", DateUtil.getCurDate());
                String dirName = SysConstant.CREAT_POSTER_PICTURE_OSS_DIR + userId + "/" + formatDate + "/";

                // 上传到oss
                AliyunOssClientUtil.uploadFileByLocalFile(targetFileImg, dirName + fileName);

                outputImgPath = SysConstant.CREAT_POSTER_PICTURE_OSS_ACCESS_PREFIX + dirName + fileName;

//                // 生成图片结果文件夹路径
//                outputImgPath = "C:\\Users\\Administrator\\Desktop\\海报模板\\result\\";
//                File resultImg = new File(outputImgPath + UUID.randomUUID().toString() + ".png");
//                ImageIO.write(bfImage, "png", resultImg);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                //在JVM退出时删除文件。也可以调用file.delete();立即删除文件。
                targetFileImg.deleteOnExit();
                // 删除临时文件
                targetFileImg.delete();
            }
        }

        // 记录一下海报生成记录
        BPosterHistory bPosterHistory = new BPosterHistory();

        bPosterHistory.setGzhCode(posterInfo.getGzhCode());
        bPosterHistory.setUserId(userIdInt);
        bPosterHistory.setPosterId(id);
        bPosterHistory.setName(bPosterInfo.getPosterName());
        bPosterHistory.setPhone(bPosterInfo.getPosterPhone());
        bPosterHistory.setComp(bPosterInfo.getPosterComp());
        bPosterHistory.setResult(outputImgPath);
        bPosterHistory.setStatus(1);
        bPosterHistory.setCreateTime(DateUtil.getCurDate());
        bPosterHistory.setUpdateTime(DateUtil.getCurDate());

        this.bPosterHistoryMapper.insert(bPosterHistory);

        return outputImgPath;
    }

    // id
    @Override
    public String getUserPosterList(String userId, String springProfilesActive, BPosterInfo bPosterInfo) throws Exception {

        // 图片结果路径
        String outputImgPath = null;

        // 查询用户基础信息
        Integer userIdInt = Integer.valueOf(userId);
        UserInfo userInfo = this.userInfoMapper.queryUserInfo(userIdInt);

//        PlatformSysInfo platformSysInfoConfig = this.sysGzhService.getPlatformSysInfo(springProfilesActive);

//        if (userInfo == null) {
//            return "请先完善个人信息";
//        }

        // id
        Integer id = bPosterInfo.getId();
//        infoKey = aesEncrypt(id.toString(), SysConstant.KEY);

//        BPosterInfo posterInfo = this.bPosterInfoMapper.queryById(id);
//        if (posterInfo == null) {
//            return "无效海报模板";
//        }

//        // 查询一下海报生成记录
//        BPosterHistory temporary = new BPosterHistory();
//
//        temporary.setGzhCode(posterInfo.getGzhCode());
//        temporary.setUserId(userIdInt);
//        temporary.setPosterId(id);
//        temporary.setName(bPosterInfo.getPosterName());
//        temporary.setPhone(bPosterInfo.getPosterPhone());
//        temporary.setComp(bPosterInfo.getPosterComp());
//        temporary.setStatus(1);
//
//        String result = this.bPosterHistoryMapper.queryOne(temporary);
//
//        // 如果之前海报生成过直接返回
//        if (StringUtils.isNotBlank(result) && result.contains(SysConstant.CREAT_POSTER_PICTURE_OSS_ACCESS_PREFIX + SysConstant.CREAT_POSTER_PICTURE_OSS_DIR + userId)) {
//            return result;
//        }

        // 会员状态
//        int vipStatus = Optional.ofNullable(userInfo.getVipStatus()).orElse(0);
//
//        // 会员海报模板
//        if (posterInfo.getMember() == 1 && vipStatus != 1) {
//            return "会员海报模板，您还不是会员";
//        }

        // 姓名
        String posterName = bPosterInfo.getPosterName();

        // 电话
        String posterPhone = bPosterInfo.getPosterPhone();

        // 公司
        String posterComp = bPosterInfo.getPosterComp();

        // 头像
        String posterHeard = bPosterInfo.getPosterHeard();

        // 文字1
        String posterText1 = bPosterInfo.getPosterText1();

        // 文字2
        String posterText2 = bPosterInfo.getPosterText2();

        // 文字3
        String posterText3 = bPosterInfo.getPosterText3();

        Date expireDate = null;

        BPosterDetails bPosterDetails = new BPosterDetails();
        bPosterDetails.setType(id);
        bPosterDetails.setStatus(1); // 删除状态 0-删除 1-正常
        List<BPosterDetails> infoList = this.bPosterDetailsMapper.queryAll(bPosterDetails);

        if (CollectionUtils.isNotEmpty(infoList)) {
            // 海报背景图片宽度、高度、底图数量
            int bcgW = 750;
            int bcgH = 1330;
            int bgNUm = 0;

            for (BPosterDetails infod : infoList) {
                if (infod.getItem() == 1011) {
                    bcgW = infod.getWidth();
                    bcgH = infod.getHeight();
                    bgNUm = bgNUm + 1;
                }
            }

            // 按照底图的宽高生成新的图片
            BufferedImage bfImage = new BufferedImage(bcgW, bcgH, BufferedImage.TYPE_INT_RGB);
            // 开启画笔
            Graphics2D g = bfImage.createGraphics();
            // 去毛边
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);


            for (BPosterDetails info : infoList) {
                // 类型
                Integer item = info.getItem();
                // 宽度
                Integer w = info.getWidth();
                // 高度
                Integer h = info.getHeight();
                // 左边距离
                Integer l = info.getLefts();
                // 上边距离
                Integer t = info.getTop();
                // 是否圆角
                Integer r = info.getRadius();
                // 角度
                Integer ro = info.getRotate();
                // 图片url
                String url = info.getImange();
                // 文字颜色
                String colorHex = info.getColor();
                // 文字大小
                Integer fontSize = 26;

                // 如果是用户的头像
                if (item == 1012) {
                    // 查询用户的头像
                    if (posterHeard != null && StringUtils.isNotBlank(posterHeard)) {
                        url = posterHeard;
                    } else if (userInfo != null && StringUtils.isNotBlank(userInfo.getAvatarUrl())) {
                        url = userInfo.getAvatarUrl();
                    } else {
                        // 关闭画笔
                        g.dispose();
                        return "请先完善头像";
                    }
                }

//                // 如果是用户的二维码
//                if (item == 1013) {
//
//                    // 查询用户的二维码
//                    if (userInfo != null && !StringUtils.isBlank(userInfo.getQrcodeUrl())) {
//                        url = userInfo.getQrcodeUrl();
//                    } else {
//                        // 关闭画笔
//                        g.dispose();
//                        return "请先完善推广二维码";
//                    }
//                }

                // 将图片url转换成 BufferedImage
                BufferedImage bimg = null;
                if (StringUtils.isNotBlank(url) && (item == 1011 || item == 1012 || item == 1014)) {
                    try {
                        URL urlfile = new URL(url.replaceAll("(/132)+$", "/0"));
                        InputStream inStream = urlfile.openStream();
                        bimg = ImageIO.read(inStream);
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.info("********** 转换异常 **********");
                    }
                }

                Color colorRgb = new Color(0, 0, 0);

                if (StringUtils.isNotBlank(colorHex) && colorHex.contains("#") && (item == 1015 || item == 1016 || item == 1017 || item == 1018 || item == 1019 || item == 1020)) {

                    colorRgb = Color.decode(colorHex);
                }

                if (info.getSize() >= 12 && (item == 1015 || item == 1016 || item == 1017 || item == 1018 || item == 1019 || item == 1020)) {

                    fontSize = info.getSize();
                }
                // 文字大小
                Font font = new Font("微软雅黑", Font.PLAIN, fontSize);

                switch (item) {
                    case 1011:
                        log.info("********** 海报底图 **********");

                        if (bimg != null) {
                            // 画海报背景图片
                            g.rotate(Math.toRadians(ro), l + w / 2, t + h / 2);
                            g.drawImage(bimg, 0, 0, bcgW, bcgH, null);
                            g.rotate(Math.toRadians(-ro), l + w / 2, t + h / 2);
                        }

                        break;
                    case 1012:
                        log.info("********** 头像 **********");

                        if (bimg != null) {

                            // 头像处理，头像半径大于等于短边的一般，变圆形。
                            if (r > 0 && r >= (w < h ? w : h) / 2) {
                                bimg = cutHeadImages1(url);
                            }

//                            bimg = getScaledImage(bimg, 750, 2);

                            // 画海报头像图片
                            g.rotate(Math.toRadians(ro), l + w / 2, t + h / 2);
                            g.drawImage(bimg, l, t, w, h, null);
                            g.rotate(Math.toRadians(-ro), l + w / 2, t + h / 2);
                        }

                        break;
                    case 1013:
                        log.info("********** 推广二维码 **********");
/*
                        // 存放在二维码中的内容，fromPage=1_海报加密id（通过 海报页面 到 微商页面）
                        String text = SysConstant.WEI_ZHAN_PATH.replace(SysConstant.frontDomain, platformSysInfoConfig.getFrontDomain()) + userId + "&fromPage=1_" + id + "&v=97";
                        // text = "http://zktmessage.zhanxiaobai.net//pages/home/index.html?closeW=false&otherUserId=723136&fromPage=1_bGQc/qZTg1blPBfrAqCfmA==&v=97";
                        // 嵌入二维码的图片路径

                        System.out.println(text);
                        String imgPath = "D:/temp/image/zhihu/v2-1ea1f4b00aac61996d58f7fedcc80058_hd.jpg";
                        imgPath = "";
                        //生成二维码
                        BufferedImage qrCodePath = QRCodeUtil.encodeReturnBufferedImage(text, imgPath, false);
*/
                        WeixinServiceDL weixinService = WeixinServiceMap.getWeixinService(springProfilesActive);
                        if (weixinService == null) {
                            weixinService = objectFactory.getObject();
                            weixinService.reSetConfigStorage(springProfilesActive);
                            WeixinServiceMap.putWeixinService(springProfilesActive, weixinService);
                        }

                        WxMpQrCodeTicket ticket = weixinService.getQrcodeService().qrCodeCreateTmpTicket(userId, 2592000);
                        expireDate = DateUtils.addDateDays(DateUtils.getCurDate(), 30);
                        File qrCodePictureFile = weixinService.getQrcodeService().qrCodePicture(ticket);
                        BufferedImage qrCodePath = ImageIO.read(qrCodePictureFile.getAbsoluteFile());

                        // 画海报推广二维码图片
                        g.rotate(Math.toRadians(ro), l + w / 2, t + h / 2);
                        g.drawImage(qrCodePath, l, t, w, h, null);
                        g.rotate(Math.toRadians(-ro), l + w / 2, t + h / 2);

                        break;
                    case 1014:
                        log.info("********** 推广大图 **********");

                        if (bimg != null) {
                            // 画海报推广大图片图片
                            g.rotate(Math.toRadians(ro), l + w / 2, t + h / 2);
                            g.drawImage(bimg, l, t, w, h, null);
                            g.rotate(Math.toRadians(-ro), l + w / 2, t + h / 2);
                        }

                        break;
                    case 1015:
                        if (StringUtils.isNotBlank(posterName)) {
                            log.info("姓名：" + posterName);

                            // 图片上写文字
                            g.setFont(font);
                            g.setColor(colorRgb);

                            FontMetrics fm = sun.font.FontDesignMetrics.getMetrics(font);
                            // 整个字符串的宽度
                            int widthN = fm.stringWidth(posterName);
                            // 字符串的高度
                            int heightN = fm.getHeight();

                            // 可以看出Height = Ascent + Descent + Leading
                            int ascent = fm.getAscent();
                            int descent = fm.getDescent();
                            int leading = fm.getLeading();
                            int height = fm.getHeight();
                            System.out.println("姓名：" + posterName);
                            System.out.printf("Height = %d\tAscent = %d\tDescent = %d\tLeading = %d", height, ascent, descent, leading);

                            g.rotate(Math.toRadians(ro), l + w / 2, t + h / 2);

                            // 1px = 0.75pt
                            g.drawString(posterName, l, t + ascent - descent);
                            g.rotate(Math.toRadians(-ro), l + w / 2, t + h / 2);
                        }
                        break;
                    case 1016:
                        if (StringUtils.isNotBlank(posterPhone)) {
                            log.info("电话：" + posterPhone);

                            // 图片上写文字
                            g.setFont(font);
                            g.setColor(colorRgb);

                            FontMetrics fm = sun.font.FontDesignMetrics.getMetrics(font);
                            // 整个字符串的宽度
                            int widthP = fm.stringWidth(posterPhone);
                            // 字符串的高度
                            int heightP = fm.getHeight();

                            // 可以看出Height = Ascent + Descent + Leading
                            int ascent = fm.getAscent();
                            int descent = fm.getDescent();
                            int leading = fm.getLeading();
                            int height = fm.getHeight();
                            System.out.println("电话：" + posterPhone);
                            System.out.printf("Height = %d\tAscent = %d\tDescent = %d\tLeading = %d", height, ascent, descent, leading);

                            g.rotate(Math.toRadians(ro), l + w / 2, t + h / 2);

                            // 1px = 0.75pt
                            g.drawString(posterPhone, l, t + ascent - descent);
                            g.rotate(Math.toRadians(-ro), l + w / 2, t + h / 2);
                        }
                        break;
                    case 1017:
                        if (StringUtils.isNotBlank(posterComp)) {
                            log.info("公司：" + posterComp);

                            // 图片上写文字
                            g.setFont(font);
                            g.setColor(colorRgb);

                            FontMetrics fm = sun.font.FontDesignMetrics.getMetrics(font);
                            // 整个字符串的宽度
                            int widthC = fm.stringWidth(posterComp);
                            // 字符串的高度
                            int heightC = fm.getHeight();

                            // 可以看出Height = Ascent + Descent + Leading
                            int ascent = fm.getAscent();
                            int descent = fm.getDescent();
                            int leading = fm.getLeading();
                            int height = fm.getHeight();
                            System.out.println("公司：" + posterComp);
                            System.out.printf("Height = %d\tAscent = %d\tDescent = %d\tLeading = %d", height, ascent, descent, leading);

                            g.rotate(Math.toRadians(ro), l + w / 2, t + h / 2);

                            // 1px = 0.75pt
                            g.drawString(posterComp, l, t + ascent - descent);
                            g.rotate(Math.toRadians(-ro), l + w / 2, t + h / 2);
                        }
                        break;
                    case 1018:
                        if (StringUtils.isNotBlank(posterText1)) {
                            log.info("文字1：" + posterText1);

                            // 图片上写文字
                            g.setFont(font);
                            g.setColor(colorRgb);

                            FontMetrics fm = sun.font.FontDesignMetrics.getMetrics(font);
                            // 整个字符串的宽度
                            int widthT1 = fm.stringWidth(posterText1);
                            // 字符串的高度
                            int heightT1 = fm.getHeight();

                            // 可以看出Height = Ascent + Descent + Leading
                            int ascent = fm.getAscent();
                            int descent = fm.getDescent();
                            int leading = fm.getLeading();
                            int height = fm.getHeight();
                            System.out.println("文字1：" + posterText1);
                            System.out.printf("Height = %d\tAscent = %d\tDescent = %d\tLeading = %d", height, ascent, descent, leading);

                            g.rotate(Math.toRadians(ro), l + w / 2, t + h / 2);

                            // 1px = 0.75pt
                            g.drawString(posterText1, l, t + ascent - descent);
                            g.rotate(Math.toRadians(-ro), l + w / 2, t + h / 2);
                        }
                        break;
                    case 1019:
                        if (StringUtils.isNotBlank(posterText2)) {
                            log.info("文字2：" + posterText2);

                            // 图片上写文字
                            g.setFont(font);
                            g.setColor(colorRgb);

                            FontMetrics fm = sun.font.FontDesignMetrics.getMetrics(font);
                            // 整个字符串的宽度
                            int widthT2 = fm.stringWidth(posterText2);
                            // 字符串的高度
                            int heightT2 = fm.getHeight();

                            // 可以看出Height = Ascent + Descent + Leading
                            int ascent = fm.getAscent();
                            int descent = fm.getDescent();
                            int leading = fm.getLeading();
                            int height = fm.getHeight();
                            System.out.println("文字2：" + posterText2);
                            System.out.printf("Height = %d\tAscent = %d\tDescent = %d\tLeading = %d", height, ascent, descent, leading);

                            g.rotate(Math.toRadians(ro), l + w / 2, t + h / 2);

                            // 1px = 0.75pt
                            g.drawString(posterText2, l, t + ascent - descent);
                            g.rotate(Math.toRadians(-ro), l + w / 2, t + h / 2);
                        }
                        break;
                    case 1020:
                        if (StringUtils.isNotBlank(posterText3)) {
                            log.info("文字3：" + posterText3);

                            // 图片上写文字
                            g.setFont(font);
                            g.setColor(colorRgb);

                            FontMetrics fm = sun.font.FontDesignMetrics.getMetrics(font);
                            // 整个字符串的宽度
                            int widthT3 = fm.stringWidth(posterText3);
                            // 字符串的高度
                            int heightT3 = fm.getHeight();

                            // 可以看出Height = Ascent + Descent + Leading
                            int ascent = fm.getAscent();
                            int descent = fm.getDescent();
                            int leading = fm.getLeading();
                            int height = fm.getHeight();
                            System.out.println("文字3：" + posterText3);
                            System.out.printf("Height = %d\tAscent = %d\tDescent = %d\tLeading = %d", height, ascent, descent, leading);

                            g.rotate(Math.toRadians(ro), l + w / 2, t + h / 2);

                            // 1px = 0.75pt
                            g.drawString(posterText3, l, t + ascent - descent);
                            g.rotate(Math.toRadians(-ro), l + w / 2, t + h / 2);
                        }
                        break;
                    default:
                        log.info("未知 item");
                }
                log.info("你的 item 是 " + item + "\n");

            }

            // 关闭画笔
            g.dispose();

            // 输入流
            File targetFileImg = null;
            // 文件名
            String fileName = UUID.randomUUID().toString() + ".png";
//            fileName = "test.png";

            try {
                // 临时文件
                targetFileImg = File.createTempFile(UUID.randomUUID().toString(), "tmp");
                ImageIO.write(bfImage, "png", targetFileImg);

                log.info("[Poster-Image-Name] = " + fileName);

                String formatDate = DateUtil.getFormatDate("yyyy-MM-dd", DateUtil.getCurDate());
                String dirName = SysConstant.CREAT_POSTER_PICTURE_OSS_DIR + userId + "/" + formatDate + "/";

                // 上传到oss
                AliyunOssClientUtil.uploadFileByLocalFile(targetFileImg, dirName + fileName);

                outputImgPath = SysConstant.CREAT_POSTER_PICTURE_OSS_ACCESS_PREFIX + dirName + fileName;

//                // 生成图片结果文件夹路径
//                outputImgPath = "C:\\Users\\Administrator\\Desktop\\海报模板\\result\\";
//                File resultImg = new File(outputImgPath + UUID.randomUUID().toString() + ".png");
//                ImageIO.write(bfImage, "png", resultImg);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                //在JVM退出时删除文件。也可以调用file.delete();立即删除文件。
                targetFileImg.deleteOnExit();
                // 删除临时文件
                targetFileImg.delete();
            }
        }

        // 记录一下海报生成记录
        BPosterHistory bPosterHistory = new BPosterHistory();

        bPosterHistory.setGzhCode(springProfilesActive);
        bPosterHistory.setUserId(userIdInt);
        bPosterHistory.setPosterId(id);
        bPosterHistory.setName(bPosterInfo.getPosterName());
        bPosterHistory.setPhone(bPosterInfo.getPosterPhone());
        bPosterHistory.setComp(bPosterInfo.getPosterComp());
        bPosterHistory.setResult(outputImgPath);
        bPosterHistory.setStatus(1);
        bPosterHistory.setExpireTime(expireDate);
        bPosterHistory.setCreateTime(DateUtil.getCurDate());
        bPosterHistory.setUpdateTime(DateUtil.getCurDate());

        this.bPosterHistoryMapper.insert(bPosterHistory);

        return outputImgPath;
    }

    @Override
    public List<BPosterInfo> getPosterInfoByGzhCode(String gzhCode) {
        return bPosterInfoMapper.getPosterInfoByGzhCode(gzhCode);
    }

}